package com.demo.command.order;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import com.demo.command.infras.CommandExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Slf4j
public class OrderInsertCommandExecutor implements CommandExecutor<OrderInsertCommandBuffer> {

  private static final String SQL = "INSERT INTO ITEM_ORDER(ID, ITEM_ID, USER_ID) VALUES (?, ?, ?)";

  private JdbcTemplate jdbcTemplate;

  public OrderInsertCommandExecutor(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public void execute(OrderInsertCommandBuffer commandBuffer) {

    List<OrderInsertCommand> commands = commandBuffer.get();
    if (CollectionUtil.isEmpty(commands)) {
      return;
    }

    List<Object[]> args = commands.stream().map(cmd -> new Object[] {UUID.fastUUID().toString(), cmd.getItemId(), cmd.getUserId() })
        .collect(toList());

    try{
      jdbcTemplate.batchUpdate(SQL, args);
      commands.forEach(command -> log.info("Executed:{}", command.toString()));
    } catch (Exception e) {
      commands.forEach(command -> log.error("Failed:{}", command.toString()));
      log.error(e.getMessage());
    }

  }

}
